package com.usian.admin.service.imlp;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {


    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.参数校验
        if (StringUtils.isEmpty (dto.getName ()) || StringUtils.isEmpty (dto.getPassword ())) {
            return ResponseResult.errorResult (AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }

        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<> ();
        queryWrapper.eq (AdUser::getName, dto.getName ());

        List<AdUser> adUsers = this.list (queryWrapper);
        if (null == adUsers || adUsers.size () != 1) {
            return ResponseResult.errorResult (AppHttpCodeEnum.PARAM_REQUIRE, "用户名不存在");
        }
        AdUser adUser = adUsers.get (0);
        String mdPassword = DigestUtils.md5DigestAsHex ((dto.getPassword () + adUser.getSalt ()).getBytes ());

        if (!adUser.getPassword ().equals (mdPassword)){
            return ResponseResult.errorResult (AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        String token = AppJwtUtil.getToken (adUser.getId ().longValue ());
        Map<String, Object> resultMap = Maps.newHashMap ();
        resultMap.put ("token",token);
        adUser.setSalt ("");
        adUser.setPassword ("");
        resultMap.put ("user",adUser);

        return ResponseResult.okResult (resultMap);
    }
}
